﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Documents;
using Microsoft.Azure;
using WebDocDB.Managers;

namespace WebDocDB.DocumentDBManager
{
    public class DatabasesManager : IDatabasesManager
    {
        private DocumentClient _client;
        private AccountSettings _accountSettings;

        public DatabasesManager(IAccountManager accountManager)
        {
            _accountSettings = accountManager.GetAccountSettings();

            _client = new DocumentClient(new Uri(_accountSettings.EndpointUrl), _accountSettings.MasterKey,
                   new ConnectionPolicy { ConnectionMode = _accountSettings.ConnectionMode, ConnectionProtocol = _accountSettings.Protocol });
        }

        public async Task<List<WebDocDB.Models.Database>> GetAllDatabases()
        {
            FeedResponse<Database> databases = await _client.ReadDatabaseFeedAsync();

            var dbList = new List<WebDocDB.Models.Database>();

            foreach (Database db in databases)
            {
                dbList.Add(new WebDocDB.Models.Database() { ID = db.Id, Link = db.SelfLink });
            }

            return dbList;
        }


        public async Task AddDatabase(string databaseName)
        {
            try
            {
                var response = await _client.CreateDatabaseAsync(new Database(){ Id = databaseName});
                //var database = await RetrieveOrCreateDatabaseAsync(databaseName)                
            }
            catch (AggregateException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public async Task DeleteDatabase(string databaseLink)
        {
            try
            {
                var response = await _client.DeleteDatabaseAsync(databaseLink);
                
            }
            catch (AggregateException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
